package my.netty.channel.nio;

import my.netty.channel.EventLoop;
import my.netty.channel.WritableChannel;
import my.netty.exception.ChannelException;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

public class NioSocketChannel extends AbstractNioSocketChannel implements WritableChannel {

    private final SocketChannel socketChannel;

    public NioSocketChannel() {
        try {
            this.socketChannel = SocketChannel.open();
        } catch (Throwable e) {
            close();
            throw new ChannelException("open", e);
        }
    }

    public NioSocketChannel(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    @Override
    public void register(EventLoop eventLoop) {
        register(eventLoop, SelectionKey.OP_READ);
    }

    @Override
    public void writeAndFlush(ByteBuffer buf) throws IOException {
        socketChannel.write(buf);
    }

    public SocketChannel javaChannel() {
        return socketChannel;
    }
}
